package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * 表示一个交换机
 */
public class Exchange {
    //用 name 作为交换机的唯一标识符
    private String name;

    //交换机类型 DIRECT FANOUT TOPIC
    private ExchangeType type = ExchangeType.DIRECT;

    //是否持久化
    private boolean durable = false;

    //是否自动删除
    private boolean autoDelete = false;

    //配置额外参数
    //后续会使用转换成JSON字符串进行存储 因为SQLite里没有键值对存储的形式
    private Map<String,Object> arguments = new HashMap<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }


    //这组getter 和 setter 是与数据库交互进行使用的
    public String getArguments(){
        //将 arguments 转换成 JSON 字符串存入数据库,解决数据库不能存储键值对的问题
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //出现异常了就返回空字符串
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        //数据库读取数据 调用 setter方法
        //此时在setter方法内组装Map对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String,Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //Java 内部代码使用的 getter 和 setter.方便获取arguments的key value值
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key,Object value){
        arguments.put(key,value);
    }

    //插入一个 Arguments 的Map
    public void setArguments(Map<String,Object> arguments){
        this.arguments = arguments;
    }
}
